package com.stu.controller;

import com.alibaba.fastjson.JSON;
import com.stu.service.TestVmwareApiService;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.ElementDescription;
import com.vmware.vim25.PerfCounterInfo;
import com.vmware.vim25.PerformanceDescription;
import com.vmware.vim25.mo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: learn_used_code
 * @packageName: com.stu.controller
 * @className: com.stu.controller-> TestServiceInstanceController
 * @createDate: 2021-11-22 10:11
 * @author: ZhangSheng
 * @version: 1.0
 * @description:
 */
@Slf4j
@RestController
@RequestMapping(value = "/test")
@Api(tags = {"Test-VC"},description = "测试链接VC信息接口1")
public class TestServiceInstanceController {

    @Autowired
    @Qualifier("testServiceInstance")
    private TestVmwareApiService testVmwareApiService;

    @ApiOperation(value = "1、实例化vcenter实例", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-connect")
    public String testServiceInstance(){
        ServiceInstance connection = null;
        try {
            connection = testVmwareApiService.connection();
        } catch (MalformedURLException e) {
            log.info("message malformedURLException:{}",e.getMessage());
            return "URL解析失败";
        } catch (RemoteException e) {
            log.info("message remoteException:{}",e.getMessage());
            return "远程连接失败";
        }
        AboutInfo ai = connection.getAboutInfo();
        String format = MessageFormat.
                format("vc-id :{0},apiType:{1},apiVersion:{2},version:{3}",
                        ai.getInstanceUuid(),
                        ai.getApiType(),
                        ai.getApiVersion(), ai.getVersion());
        log.info("vc-id :{},apiType:{},apiVersion:{},version:{}",ai.getInstanceUuid(),ai.getApiType(),ai.getApiVersion(),ai.getVersion());
        return format;
    }

    @ApiOperation(value = "2、实例化宿主机列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-hostSystem")
    public String testHostSystem() throws RemoteException {
        HostSystem[] hostSystemList = testVmwareApiService.getHostSystemList();
        log.info("性能采集HostSystem数量-{}", hostSystemList.length);
        return MessageFormat.format("性能采集HostSystem数量-{0}",hostSystemList.length);
    }


    @ApiOperation(value = "3、实例化虚拟机列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-get-vmList")
    public String testVm() throws RemoteException {
        VirtualMachine[] virtualMachineList = testVmwareApiService.getVirtualMachineList();
        return MessageFormat.format("获取到虚拟机 {0} 台",virtualMachineList.length);
    }

    @ApiOperation(value = "测试连接获取性能管理对象监控项", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-platfor")
    public String testPlaformance(){
        PerformanceManager performanceManager = testVmwareApiService.getServiceInstance().getPerformanceManager();
        PerfCounterInfo[] perfCounter = performanceManager.getPerfCounter();
        for (int i = 0; i < perfCounter.length; i++) {
            log.info("perfor-counter{} : {},counter-key : {},counter-groupinfo : {}",i,perfCounter[i],perfCounter[i].getKey(),perfCounter[i].getGroupInfo());
            log.info("count-level: {}",perfCounter[i].getLevel());
            log.info("count-associatedCounterId:{}",perfCounter[i].getAssociatedCounterId());
        }
        testVmwareApiService.getServiceInstance().getServerConnection().logout();
        return JSON.toJSONString(perfCounter);
    }

    @ApiOperation(value = "测试连接获取性能管理对象描述", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-performance-desc")
    public String testDesc(){
        PerformanceManager performanceManager = testVmwareApiService.getServiceInstance().getPerformanceManager();
        PerformanceDescription description = performanceManager.getDescription();
        ElementDescription[] counterType = description.getCounterType();
        for (int i = 0; i < counterType.length; i++) {
            log.info("Description-Key:{},DynamicType:{},Label:{}",counterType[i].getKey(),counterType[i].getDynamicType(),counterType[i].getLabel());
        }
        testVmwareApiService.getServiceInstance().getServerConnection().logout();
        return JSON.toJSONString(counterType);
    }

    @ApiOperation(value = "测试连接宿主机获取MOR", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-host-system-info")
    public String testHostSystemInfo() throws RemoteException {
        List<String> ids = new ArrayList<>();
        HostSystem[] hostSystemList = testVmwareApiService.getHostSystemList();
        for (int i = 0; i < hostSystemList.length; i++) {
            ids.add(MessageFormat.format("resources mor type ===> {0}, value ===> {1}"
                    ,hostSystemList[i].getMOR().getType()
                    ,hostSystemList[i].getMOR().getVal()));
            String uuid = hostSystemList[i].getSummary().getHardware().getUuid();
            log.info("Hardware-uuid={}", uuid);
        }
        return JSON.toJSONString(ids);
    }

    @ApiOperation(value = "测试连接宿主信息", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-host-system-info_2")
    public String testHostSystemInfo_FOR() throws RemoteException {
        List<String> ids = new ArrayList<>();
        HostSystem[] hostSystemList = testVmwareApiService.getHostSystemList();
        for (int i = 0; i < hostSystemList.length; i++) {
            ids.add(MessageFormat.format("resources mor type ===> {0}, value ===> {1}",hostSystemList[i].getMOR().getType(),hostSystemList[i].getMOR().getVal()));
        }
        return JSON.toJSONString(ids);
    }

    @ApiOperation(value = "4、实例化vmware资源池列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-pool")
    public String testGetPool() throws RemoteException {
        ResourcePool[] resourcePoolList = testVmwareApiService.getResourcePoolList();
        return MessageFormat.format("获取到的资源池数量： {0} 台;",resourcePoolList.length);
    }

    @ApiOperation(value = "获取vmware资源池列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-pool-list")
    public String testGetPoolList() throws RemoteException {
        StringBuilder resourcePool = new StringBuilder();
        ResourcePool[] resourcePoolList = testVmwareApiService.getResourcePoolList();
        for (int i = 0; i < resourcePoolList.length; i++) {
            resourcePool.append("POOL-MOR: ").append(resourcePoolList[i].getMOR().getVal()).append("\t")
                    .append("POOL-NAME: ").append(resourcePoolList[i].getName()).append("\t")
                    .append("SUMMARY-POOL-NAME: ").append(resourcePoolList[i].getSummary().getName()).append("\t")
                    .append("POOL-CPU-ALLOCATION: ").append(resourcePoolList[i].getSummary().getConfig().getCpuAllocation().getLimit()).append("\t")
                    .append("POOL-MEMORY-ALLOCATION: ").append(resourcePoolList[i].getSummary().getConfig().getMemoryAllocation().getLimit()).append("\t")
                    .append(System.getProperty("line.separator"));
        }
        return resourcePool.toString();
    }

    @ApiOperation(value = "获取虚拟机信息列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-get-vmSummer")
    public String testVmSummer() throws RemoteException {
        StringBuilder  stringBuilder = new StringBuilder();
        VirtualMachine[] virtualMachineList = testVmwareApiService.getVirtualMachineList();
        for (int i = 0; i < virtualMachineList.length; i++) {
            VirtualMachine vm = virtualMachineList[i];
            if (vm.getSummary().getConfig().getName().equals("BAC_APP_15")) {
                stringBuilder.append("vm-name: ")
                        .append(vm.getSummary().getConfig().getName())
                        .append("\t")
                        .append("summary-vm-instance-uuid: ")
                        .append(vm.getSummary().getConfig().getInstanceUuid())
                        .append("\t")
                        .append("guestId: ")
                        .append(vm.getConfig().getGuestId())
                        .append("\t")
                        .append("vm-uuid: ")
                        .append(vm.getConfig().getUuid())
                        .append("\t")
                        .append("mor: ")
                        .append(vm.getMOR().getVal())
                        .append("\t")
                        .append("config-instance-uuid: ")
                        .append(vm.getConfig().getInstanceUuid())
                        .append("\t")
                        .append("config-location-id: ")
                        .append(vm.getConfig().getLocationId())
                        .append("\t")
                        .append("vc-instance-id: ")
                        .append(testVmwareApiService.getServiceInstance().getAboutInfo().getInstanceUuid())
                        .append(System.getProperty("line.separator"));
            }
        }
        return stringBuilder.toString();
    }


    @ApiOperation(value = "获取数据中心列表", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-print-datacenter")
    public String testDatacenterList() throws RemoteException {
        Datacenter[] datacenterList = testVmwareApiService.getDatacenterList();
        StringBuilder dataCenter = new StringBuilder();
        for (int i = 0; i < datacenterList.length; i++) {
            String name = datacenterList[i].getName();
            dataCenter.append("datacenter-name:").append(name).append("\t")
                    .append("datacenter-mor:").append(datacenterList[i].getMOR().getVal()).append("\t")
                    .append("default-hardware-version-key:").append(datacenterList[i].getConfiguration().getDefaultHardwareVersionKey()).append("\t")
                    .append(System.getProperty("line.separator"));
        }
        return dataCenter.toString();
    }

    //ClusterComputeResource[] getClustComputeResourceList() throws RemoteException;
    //
    //Datastore[] getDatastoreList() throws RemoteException;
    //
    //Network[] getNetworks() throws RemoteException;

    @ApiOperation(value = "获取集群列表",response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。", response = String.class)})
    @GetMapping("/test-print-clust")
    public String testClustPrint() throws RemoteException {
        ClusterComputeResource[] clustComputeResourceList = testVmwareApiService.getClustComputeResourceList();
        StringBuilder clust = new StringBuilder();
        for (int i = 0; i < clustComputeResourceList.length; i++) {
            clust.append("Cluster-Name: ").append(clustComputeResourceList[i].getName()).append("\t")
                 .append("Cluster-MOR: ").append(clustComputeResourceList[i].getMOR().getVal()).append("\t")
                 .append("Cluster-Total-Cpu: ").append(clustComputeResourceList[i].getSummary().getTotalCpu()).append("\t")
                 .append("Cluster-Total-Memory: ").append(clustComputeResourceList[i].getSummary().getTotalMemory()).append("\t")
                    .append(System.getProperty("line.separator"));
        }
        return clust.toString();
    }



}
